export interface Resp<T> {
  status: number
  message: string
  data: T
}

export type RespType<T> = Promise<Resp<T>>

export function get<T = any>(
  url: string,
  params?: Record<string, number | string> | any
): RespType<T> {
  let newUrl = url
  if (params) {
    const paramObj = new URLSearchParams()
    Object.keys(params).reduce((acc, cur) => {
      acc.append(cur, String(params[cur]))
      return acc
    }, paramObj)
    const paramsStr = paramObj.toString()
    newUrl = `${url}?${paramsStr}`
  }
  return fetch(newUrl, {
    method: "GET",
    credentials: "same-origin",
  }).then((res) => res.json())
}

export function post<T = any>(url: string, params: any): RespType<T> {
  return fetch(url, {
    method: "POST",
    credentials: "same-origin",
    body: JSON.stringify(params),
    headers: {
      "Content-Type": "application/json",
    },
  }).then((res) => res.json())
}
